<?php

class Admin_Plugin_Auth extends Zend_Controller_Plugin_Abstract
{
    public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
    {
        $moduleName = $this->_request->getModuleName();

        if ($moduleName != 'admin') {
            return false;
        }

        $resource   = Zend_Controller_Action_HelperBroker::getStaticHelper('Resource');
        $redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('Redirector');
        $auth       = Zend_Controller_Action_HelperBroker::getStaticHelper('Auth');
        $controller = $this->getRequest()->getControllerName();
        $action     = $this->getRequest()->getActionName();

        if (!$auth->isLoggedIn()) {
            $redirector->gotoUrlAndExit('/auth/login');
        }

        if (Model_Member::ROLE_ADMINISTRATOR != $auth->getCurrentMember()->role) {
            $redirector->gotoUrlAndExit('/');
        }

        $this->_setViewVars();
    }

    protected function _setViewVars()
    {
        $auth         = Zend_Controller_Action_HelperBroker::getStaticHelper('auth');
        $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer');

        $viewRenderer->view->isLoggedIn = false;
        $viewRenderer->view->authMember = null;

        if ($auth->isLoggedIn()) {
            $viewRenderer->view->isLoggedIn = true;
            $viewRenderer->view->authMember = $auth->getCurrentMember();
        }
    }
}